const WXAPI = require('../../../wxapi/main')
const CONFIG = require('../../../config.js')
const con = require("../../../utils/data.js");
//获取应用实例
var app = getApp()
Page({
  data: {
    inputShowed: false, // 是否显示搜索框
    inputVal: "", // 搜索框内容
    category_box_width: 750, //分类总宽度
    goodsRecommend: [], // 推荐商品
    kanjiaList: [], //砍价商品列表
    pingtuanList: [], //拼团商品列表
    kanjiaGoodsMap: {}, //砍价商品列表
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    loadingHidden: false, // loading
    userInfo: {},
    swiperCurrent: 0,
    selectCurrent: 0,
    categories: [],
    activeCategoryId: 0,
    goods: [],
    
    scrollTop: 0,
    loadingMoreHidden: true,

    coupons: [],

    curPage: 1,
    pageSize: 20,
    cateScrollTop: 0,
    article:'商品描述',
    mybanners:[],
    myposter:[],
    qdyl:'',
    jfzq: '',
    yhq: '',
    xsyh: '',
    axyz: '',
    pt: '',
    bmfw: '',
    cprz: '',
    hhr: '',
    hfcz: '',
    mygoods:'',
    discount:''
  },
  goSearch() {
    wx.navigateTo({
      url: '../../goods/goods',
    })
  },
  // 弹出红包
  onReady() {
    // this.showModal()
  },
  showModal() {
    this.setData({
      modalName: 'Image'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  tabClick: function(e) {
    let offset = e.currentTarget.offsetLeft;
    if (offset > 150) {
      offset = offset - 150
    } else {
      offset = 0;
    }
    this.setData({
      activeCategoryId: e.currentTarget.id,
      curPage: 1,
      cateScrollTop: offset
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  //事件处理函数
  swiperchange: function(e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  toDetailsTap: function(e) {
    wx.navigateTo({
      url: "/pages/merchant/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function(e) {
    if (e.currentTarget.dataset.id != 0) {
      wx.navigateTo({
        url: "/pages/merchant/goods-details/index?id=" + e.currentTarget.dataset.id
      })
    }
  },
  bindTypeTap: function(e) {
    this.setData({
      selectCurrent: e.index
    })
  },
 

  onLoad: function(e) { 
    const that = this
    // 图标获取
    wx.request({
      url: 'https://www.brvpmusic.com/api/picture/home_page',
      // url: con.index_mybanners,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // console.log('图标获取成功');
        // console.log(res.data);
        // console.log(res.data.body[0].hUrl);
        that.setData({
          qdyl: res.data.body[0].hUrl,
          jfzq: res.data.body[1].hUrl,
          yhq: res.data.body[2].hUrl,
          xsyh: res.data.body[3].hUrl,
          axyz: res.data.body[4].hUrl,
          pt: res.data.body[5].hUrl,
          bmfw: res.data.body[6].hUrl,
          cprz: res.data.body[7].hUrl,
          hhr: res.data.body[8].hUrl,
          hfcz: res.data.body[9].hUrl,
        })
      },
      fail: function (res) {
        console.log('返回失败');
      }
    })
    // 轮播图获取
    wx.request({
      // url: 'http://3s.dkys.org:25333/api/banner/list',
      url:con.index_mybanners,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.setData({
          mybanners: res.data.data,
        })
      },
      fail: function (res) {
        console.log('返回失败');
      }
    })
    // 首页商品获取
    wx.request({
      // url: 'http://192.168.0.105:8080/api/products/getList',
       url: 'https://www.brvpmusic.com/api/products/getList',
      // url: 'http://2624519ed2.qicp.vip/api/products/getList',
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log('首页商品获取成功');
        console.log(res.data.body);
        console.log(res.data.body.pPostage);
        console.log('长度'+res.data.body.length);
        var result = res.data.body;
        console.log(result[0].pictureStorages[0].pimgurl);
        console.log('类型:'+typeof(result));
        if(wx.getStorageSync("discount")!=null||wx.getStorageSync("discount")!=""){
            that.setData({
                'discount': wx.getStorageSync("discount"),
                'mygoods': res.data.body,
            })
        }else {
            that.setData({
                'discount': 0,
                'mygoods': res.data.body,
            })
        }
      },
      fail: function (res) {
        console.log('返回失败');
      }
    })
    // 首页广告图
    wx.request({
      // url: 'http://3s.dkys.org:25333/api/advertisement/list',
      url:con.index_myposter,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.setData({
          myposter: res.data.data,
        })
      },
      fail: function (res) {
        console.log('返回失败');
      }
    })
    // -------------
    wx.showShareMenu({
      withShareTicket: true
    }) 
    
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene)
      if (scene) {        
        wx.setStorageSync('referrer', scene.substring(11))
      }
    }
    
    /**
     * 示例：
     * 调用接口封装方法
     */
    WXAPI.banners({
      type: 'new'
    }).then(function(res) {
      if (res.code == 700) {
        wx.showModal({
          title: '提示',
          content: '请在后台添加 banner 轮播图片，自定义类型填写 new',
          showCancel: false
        })
      } else {
        that.setData({
          banners: res.data
        });
      }
    }).catch(function(e) {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    })
    WXAPI.goodsCategory().then(function(res) {

      let categories = [];
      if (res.code == 0) {
        categories = categories.concat(res.data)
      }
      const _n = Math.ceil(categories.length / 2)
      // const _n = Math.ceil(categories.length)
      that.setData({
        categories: categories,
        category_box_width: 150 * _n,
        activeCategoryId: 0,
        curPage: 1
      });
      that.getGoodsList(0);
    })
    WXAPI.goods({
      recommendStatus: 1
    }).then(res => {
      if (res.code === 0){
        that.setData({
          goodsRecommend: res.data
        })
      }      
    })
    that.getCoupons()
    that.getNotice()
    that.kanjiaGoods()
    that.pingtuanGoods()
  },
  onPageScroll(e) {
    let scrollTop = this.data.scrollTop
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  getGoodsList: function(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    var that = this;
    wx.showLoading({
      "mask": true
    })
    WXAPI.goods({
      categoryId: categoryId,
      nameLike: that.data.inputVal,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    }).then(function(res) {
      wx.hideLoading()
      if (res.code == 404 || res.code == 700) {
        let newData = {
          loadingMoreHidden: false
        }
        if (!append) {
          newData.goods = []
        }
        that.setData(newData);
        return
      }
      let goods = [];
      if (append) {
        goods = that.data.goods
      }
      for (var i = 0; i < res.data.length; i++) {
        goods.push(res.data[i]);
      }
      that.setData({
        loadingMoreHidden: true,
        goods: goods,
      });
    })
  },
  getCoupons: function() {
    var that = this;
    WXAPI.coupons().then(function (res) {
      if (res.code == 0) {
        that.setData({
          coupons: res.data
        });
      }
    })
  },
  onShareAppMessage: function() {    
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + CONFIG.shareProfile,
      path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  getNotice: function() {
    var that = this;
    WXAPI.noticeList({pageSize: 5}).then(function (res) {
      if (res.code == 0) {
        that.setData({
          noticeList: res.data
        });
      }
    })
  },
  toSearch: function() {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  onReachBottom: function() {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.getGoodsList(this.data.activeCategoryId, true)
  },
  onPullDownRefresh: function() {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId)
    this.onLoad();
    wx.stopPullDownRefresh()
  },
  // 以下为搜索框事件
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  // 以下为砍价业务
  kanjiaGoods(){
    const _this = this
    WXAPI.kanjiaList().then(function (res) {
      if (res.code == 0) {
        _this.setData({
          kanjiaList: res.data.result,
          kanjiaGoodsMap: res.data.goodsMap
        })
      }
    })
  },
  goCoupons: function (e) {
    wx.navigateTo({
      url: "/pages/coupons/index"
    })
  },
  pingtuanGoods(){ // 获取团购商品列表
    const _this = this
    WXAPI.goods({
      pingtuan: true
    }).then(res => {
      if (res.code === 0) {
        _this.setData({
          pingtuanList: res.data
        })
      }
    })
  },
  // 页面跳转
  goqdyl: function () {
    wx.navigateTo({
      url: "/pages/sign/sign_in"
    })
  },
  gowdsc: function () {
    wx.navigateTo({
      url: "/pages/user_goods_collection/index"
    })
  },
  gojfzq: function () {
    wx.navigateTo({
      url: "/pages/jfzq/jfzq"
    })
  },
  goyhq: function () {
    wx.navigateTo({
      url: "/pages/coupons/index"
    })
  },
  goxsyh: function () {
    wx.navigateTo({
      url: "/pages/xsyh/xsyh"
    })

  },
  gojjsl: function () {
    wx.navigateTo({
      url: "/pages/fund/shuoming"
    })
  },
  gopt: function () {
    wx.navigateTo({
      url: "/pages/pt/pt"
    })

  },
  gobmfw: function () {
    wx.navigateTo({
      url: "/pages/bmfw/bmfw"
    })
  },
  szsq: function () {
    wx.navigateTo({
      url: "/pages/my/Distributor/Distributor"
    })
  },
  goptjm: function () {
    wx.navigateTo({
      url: "/pages/my/Alliance/Alliance"
    })
  },
  gohfcz: function () {
    wx.navigateTo({
      url: "/pages/hfcz/hfcz"
    })
    // wx.showToast({
    //   title: '尚未开通该功能'
    // })

  },
  // 跳转到美容美发
  goBarberShop() {
    wx.navigateTo({
      url: '/pages/bmfw/barber-shop/index',
    })
  },
})